<?php


namespace app\model;

use think\Model;
use think\facade\Db;
use app\model\CarModel;
use app\model\QuotationTransportModel;
use app\model\RemarkModel;
use app\model\Attachment as AttachmentModel;
use app\model\VehicleModel;
use app\model\DeliveryModel;

class QuotationModel extends Model
{
    protected $table = "store_quotation";

    /**
     * @param $param
     * @return array|\think\Collection|Db[]
     * @notes 报价详情
     * @author: dongdong
     * @date: 2025/1/10 18:50
     */
    public function quotation_list($param)
    {
        try {
            $CarModel = new CarModel();
            $QuotationTransportModel = new QuotationTransportModel();
            $RemarkModel = new RemarkModel();
            $Attachment = new Attachment();

            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;
            $page = ($page - 1) * $limit;

            $field1 = $param['synthesis_order'] ?? '';
            $field2 = $param['price_order'] ?? '';
            $field3 = $param['validity_order'] ?? '';

            $is_transport = $param['is_transport'] ?? 0;

            if ($is_transport != 1) {
                // 初始化排序条件数组
                $orderClauses = [];

                // 根据接收的字段构建排序规则
                if (!empty($field1)) {
                    $orderClauses[] = "synthesis " . ($field1 == 1 ? "ASC" : "DESC");
                }
                if (!empty($field2)) {
                    $orderClauses[] = "price " . ($field2 == 1 ? "ASC" : "DESC");
                }
                if (!empty($field3)) {
                    $orderClauses[] = "validity " . ($field3 == 1 ? "ASC" : "DESC");
                }
                if (!empty($orderClauses)) {
                    $list = Db::table($this->table)->where(['delivery_id' => $param['delivery_id'],"is_deleted"=>0])->order(implode(", ", $orderClauses))->limit($page, $limit)->select();
                } else {
                    $list = Db::table($this->table)->where(['delivery_id' => $param['delivery_id'],"is_deleted"=>0])->limit($page, $limit)->select();
                }
                $arr = [];
                foreach ($list as $k => &$v) {
                    $arr_child = [];
                    $v['user'] = Db::connect("fast_mysql")->table("fa_user")->where(['id' => $v['user_id']])->field("id,username,username_ru,mobile,level,avatar")->find();
                    $v['user_info'] = Db::connect("fast_mysql")->table("fa_user_info")->where(["user_id" => $v['user_id']])->field("identity_id,country,profile,profile_ru")->find();

                    $v['remark'] = $RemarkModel->find($v['remark_id']);
                    $v['transport_remark'] = $RemarkModel->find($v['transport_remark_id']);

                    $v['attachment'] = $Attachment->lists($this->table, $v['attachment_id']);
                    $v['transport_attachment'] = $Attachment->lists($this->table, $v['transport_attachment_id']);


                    $v['transport_set'] = $QuotationTransportModel->transport_set($v['transport_set']);
                    foreach ($v['transport_set'] as $kk => &$vv) {
                        $arr_child = [];
                        $v['transport_set'][$kk]['car'] = $CarModel->info($vv['car_id']);
                        array_push($arr_child, $v['transport_set']);
                    }
                    $str = $v;
                    $str['transport_set'] = $arr_child;
                    array_push($arr, $str);
                }
                return $arr;

            } else {
                // 初始化排序条件数组
                $orderClauses = [];

                // 根据接收的字段构建排序规则
                if (!empty($field1)) {
                    $orderClauses[] = "synthesis " . ($field1 == 1 ? "ASC" : "DESC");
                }
                if (!empty($field2)) {
                    $orderClauses[] = "price " . ($field2 == 1 ? "ASC" : "DESC");
                }
                if (!empty($field3)) {
                    $orderClauses[] = "validity " . ($field3 == 1 ? "ASC" : "DESC");
                }
                if (!empty($orderClauses)) {
                    $list = $QuotationTransportModel->where(['delivery_id' => $param['delivery_id'],"is_deleted"=>0])->order(implode(", ", $orderClauses))->limit($page, $limit)->select();
                } else {
                    $list = $QuotationTransportModel->where(['delivery_id' => $param['delivery_id'],"is_deleted"=>0])->limit($page, $limit)->select();
                }
                foreach ($list as $kk => &$vv) {
                    $vv['user'] = Db::connect("fast_mysql")->table("fa_user")->where(['id' => $vv['user_id']])->field("id,username,username_ru,mobile,level,avatar")->find();
                    $vv['user_info'] = Db::connect("fast_mysql")->table("fa_user_info")->where(["user_id" => $vv['user_id']])->field("identity_id,country,profile,profile_ru")->find();

                    $vv['car'] = $CarModel->info($vv['car_id']);
                }
                return $list;

            }
        } catch (\Exception $e) {
            return [];
        }
    }


    /**
     * @param $param
     * @return int
     * @notes 运输报价
     * @author: dongdong
     * @date: 2025/1/14 16:32
     */
    public function freight_quotation($param)
    {
        Db::startTrans();
        try {

            $dd['delivery_id'] = $param['delivery_id'];
            $dd['user_id'] = $param['user_id'];
            $dd['price'] = $param['price'];
            $dd['price_unit'] = $param['price_unit'];
            $dd['validity'] = $param['validity'];
            $dd['quotation_end_at'] = $param['quotation_end_at'] ?? '';
            $dd['create_at'] = date('Y-m-d H:i:s');

            $remark = $param['remark'] ?? '';
            $transport_remark = $param['transport_remark'] ?? '';

            $QuotationModel = new QuotationModel();

            $find = $QuotationModel->where(['user_id'=>$param['user_id'],'delivery_id'=>$param['delivery_id'],'is_deleted'=>0])->find();
            if(!empty($find)){
                Db::commit();
                return '您已报过价啦,请不要重复报价';
            }


            $insertGetId = $QuotationModel->insertGetId($dd);

            $AttachmentModel = new AttachmentModel();
            $str = $str2 = '';
            if ($param['images']) {
                $list_arr = explode(',', $param['images']);
                foreach ($list_arr as $k => &$v) {
                    $str .= $AttachmentModel->insertGetId(['user_id' => $param['user_id'], 'table_name' => $this->table, 'table_id' => $insertGetId, 'path' => $v]) . ',';
                }
                $str = trim($str, ',');
            }
            if ($param['transport_images']) {
                $list_arr2 = explode(',', $param['transport_images']);
                foreach ($list_arr2 as $k => &$v) {
                    $str2 .= $AttachmentModel->insertGetId(['user_id' => $param['user_id'], 'table_name' => $this->table, 'table_id' => $insertGetId, 'path' => $v]) . ',';
                }
                $str2 = trim($str2, ',');
            }

            $RemarkModel = new RemarkModel();
            $remark_id = 0;
            $transport_remark_id = 0;

            if (!empty($remark)) {
                $remark_id = $RemarkModel::remark_id($remark, $this->table, $insertGetId);
            }
            if (!empty($transport_remark)) {
                $transport_remark_id = $RemarkModel::remark_id($transport_remark, $this->table, $insertGetId);
            }

            self::where(["id" => $insertGetId])->update(['attachment_id' => $str, 'transport_attachment_id' => $str2, 'remark_id' => $remark_id, 'transport_remark_id' => $transport_remark_id]);

            $delivery_id = $param['delivery_id'];
            Db::query("update store_delivery_attach set quote_number=quote_number+1 where delivery_id=$delivery_id");

            Db::commit();
            return 1;
        } catch (\Exception $e) {
            Db::rollback();
            return '接口错误';
        }
    }


    /**
     * @param $param
     * @return CarModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 选择车辆
     * @author: dongdong
     * @date: 2025/1/14 17:29
     */
    public function car_search($param)
    {
        $CarModel = new CarModel();
        $VehicleModel = new VehicleModel();

        $status = $param['status'];
        $mode = $param['mode'];
        $car_category_id = $param['car_category_id'];
        $where = ['is_deleted'=>0];
        if ($status) {
            $where['status'] = $status;
        }
        if ($mode) {
            $where['mode'] = $mode;
        }
        if ($car_category_id) {
            $where['car_category_id'] = $car_category_id;
        }

        $list = $CarModel->where(['user_id' => $param['user_id']])->where($where)->select();
        foreach ($list as $k => &$v) {
            $v['area'] = Db::connect('fast_mysql')->table('fa_area')->field("id,name,name_ru,mergename,mergename_ru")->where(["id" => $v['current_city_id']])->find();
            $v['car_category_name'] = $VehicleModel->field("id,title,title_ru")->where(['id' => $v['car_category_id']])->find();
        }
        return $list;
    }


    /**
     * @param $param
     * @return array
     * @notes 货代订单
     * @author: dongdong
     * @date: 2025/1/21 11:44
     */
    public function quotation_order($param)
    {
        try {
            $RemarkModel = new RemarkModel();
            $Attachment = new Attachment();
            $DeliveryModel = new DeliveryModel();
            $DeliveryStepModel = new DeliveryStepModel();

            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;
            $page = ($page - 1) * $limit;
            $user_id = $param['user_id'] ?? '';
            $status = $param['status'] ?? '';
            $goods_type = $param['goods_type'] ?? '';




            if($status==1){
                $where = "q.user_id = '$user_id'";
                if($status){
                    $where .= " and d.status='$status'";
                }
                if($goods_type==''){
                    $where .= "";
                }elseif($goods_type=='0'){
                    $where .= " and d.goods_type='$goods_type'";
                }elseif($goods_type=='1'){
                    $where .= " and d.goods_type='$goods_type'";
                }else {
                    $where .= "";
                }

                $list = Db::table($this->table)->alias("q")->join("store_delivery d","q.delivery_id=d.id")->field("q.*")
                    ->where($where)->order("q.id desc")->limit($page,$limit)->select();
                $arr = [];
                foreach ($list as $k =>&$v){
                    array_push($arr,$v);
                }

            }else{
                $where = "d.is_deleted=0 and a.cooperate_id!='' and find_in_set($user_id,cooperate_user_id)";

                if ($status) {
                    $where .= " and d.status='$status'";
                }
                if ($goods_type == '') {
                    $where .= "";
                } elseif ($goods_type == '0') {
                    $where .= " and d.goods_type='$goods_type'";
                } elseif ($goods_type == '1') {
                    $where .= " and d.goods_type='$goods_type'";
                } elseif ($goods_type == '2') {
                    $where .= " and d.abnormal_count>d.handle_count";
                } else {
                    $where .= "";
                }

                $list = Db::table("store_delivery")->alias("d")->join("store_delivery_attach a","d.id=a.delivery_id")
                    ->field("d.id,d.demand,a.cooperate_id")
                    ->where($where)->order("d.id desc")->limit($page, $limit)->select();
                $arr = [];
                foreach ($list as $k => &$v) {
                    if($v['demand']==1){
                        $v['store_quotation'] = Db::table("store_quotation_transport")->alias("q")->where(["id"=>$v['cooperate_id']])->where("q.user_id = '$user_id' and q.is_deleted=0")->find();
                    }else{
                        $v['store_quotation'] = Db::table("store_quotation")->alias("q")->where(["id"=>$v['cooperate_id']])->where("q.user_id = '$user_id' and q.is_deleted=0")->find();
                    }
                    array_push($arr, $v);
                }
            }


            foreach ($arr as $k => &$v) {

                if($status==1){
                    $delivery = $DeliveryModel->where(['id' => $v['delivery_id']])->select();
                    $v['delivery'] = $DeliveryModel->record_handle($delivery,$user_id)[0] ?? [];
                    $v['price_rank'] = 1;
                    $v['validity_rank'] = 1;
                    $v['synthesis_rank'] = 1;
                    $v['remark'] = $RemarkModel->find($v['remark_id']);
                    $v['transport_remark'] = $RemarkModel->find($v['transport_remark_id']);

                    $v['attachment'] = $Attachment->info($this->table, $v['id']);
                    $v['yuntrace'] = $DeliveryStepModel->is_have_step($v['delivery_id']);
                }else{
                    $delivery = $DeliveryModel->where(['id' => $v['id']])->select();
                    $v['delivery'] = $DeliveryModel->record_handle($delivery,$user_id)[0] ?? [];
                    $v['price_rank'] = 1;
                    $v['validity_rank'] = 1;
                    $v['synthesis_rank'] = 1;
                    $v['delivery_id'] = $v['id'];
                    $v['remark'] = [];
                    $v['transport_remark'] = [];
                    $v['attachment'] = [];

                    if($v['demand']!=1){
                        if($v['store_quotation']){
                            $v['remark'] = $RemarkModel->find($v['store_quotation']['remark_id']);
                            $v['transport_remark'] = $RemarkModel->find($v['store_quotation']['transport_remark_id']);
                        }
                    }

                    if($v['store_quotation']) {
                        $v['attachment'] = $Attachment->info($this->table, $v['store_quotation']['id']);
                    }

                    $v['yuntrace'] = $DeliveryStepModel->is_have_step($v['id']);

                }
            }
            return $arr;
        } catch (\Exception $e) {
            _d($e);
            return [];
        }
    }


    /**
     * @param $delivery_id
     * @param $user_id
     * @return QuotationModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 货代报价
     * @author: dongdong
     * @date: 2025/2/21 17:59
     */
    public function quotation_info($delivery_id,$user_id){
        $list = self::where("delivery_id=$delivery_id and user_id=$user_id and is_deleted=0")->select();
        $RemarkModel = new RemarkModel();
        $Attachment = new Attachment();
        foreach ($list as $k =>&$v){
            $v['remark'] = $RemarkModel->find($v['remark_id']);
            $v['transport_remark'] = $RemarkModel->find($v['transport_remark_id']);
            $v['attachment'] = $Attachment->lists($this->table, $v['attachment_id']);
            $v['transport_attachment'] = $Attachment->lists($this->table, $v['transport_attachment_id']);
        }
        return $list;
    }

}